<template>
  <div class="client-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #buts>
        <a-button type="primary" @click="add">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>新建人员</template>
        </a-button>
      </template>
    </pageHeader>
    <a-modal
      width="1100px"
      v-model:visible="visible"
      :title="titleName"
      @ok="handleBeforeOk"
    >
      <a-form
        auto-label-width
        ref="formData"
        :rules="rules"
        :model="form"
        layout="horizontal"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="name" :show-colon="true" label="员工名称">
              <a-input v-model="form.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :show-colon="true" label="员工工号">
              <a-input
                placeholder="系统自动生成"
                v-model="form.staffNo"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item :show-colon="true" field="gender" label="性别">
              <a-select v-model="form.gender">
                <a-option :value="1">男</a-option>
                <a-option :value="2">女</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :show-colon="true" field="mobile" label="手机号码">
              <a-input :disabled="form.id" v-model="form.mobile" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              :show-colon="true"
              field="certificateType"
              label="证件类型"
            >
              <a-select v-model="form.certificateType">
                <a-option value="身份证">身份证</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :show-colon="true" field="idNumber" label="证件号码">
              <a-input v-model="form.idNumber" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item
              :show-colon="true"
              field="userDepartmentId"
              label="所属部门"
            >
              <a-cascader
                v-model="form.userDepartmentId"
                :field-names="fieldNames"
                :options="OrganizationData"
                expand-trigger="hover"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="userPositionId" :show-colon="true" label="岗位">
              <a-select v-model="form.userPositionId">
                <a-option
                  v-for="item in stationData"
                  :value="item.id"
                  :key="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item :show-colon="true" field="role" label="角色">
              <a-select v-model="form.role">
                <a-option
                  v-for="item in roleData"
                  :value="item.id"
                  :key="item.id"
                  >{{ item.roleName }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <tableTurn
      style="margin-top: 10px"
      :tableData="Getuserlist"
      :args="args"
      ref="tableTurnRef"
    >
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.id"
        :title="item.title"
        :data-index="item.code"
        :width="180"
      >
        <template v-if="item.code === 'gender'" #cell="{ record }">
          {{ record.gender === 1 ? '男' : '女' }}
        </template>
        <template v-else-if="item.code === 'department'" #cell="{ record }">
          {{ record.department.name }}
        </template>
        <template v-else-if="item.code === 'positionId'" #cell="{ record }">
          {{ record.positionId.name }}
        </template>
        <template v-else-if="item.code === 'role'" #cell="{ record }">
          {{ record.roles.roleName }}
        </template>
        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <template v-if="record.status === 1">
            <div class="y_statusBox">
              <span>在职</span>
            </div>
          </template>
          <template v-else>
            <div class="n_statusBox">
              <span>离职</span>
            </div>
          </template>
        </template>
        <template v-else-if="item.code === 'handle'" #cell="{ record }">
          <a-tooltip :content="record.status === 1 ? '设为离职' : '设为在职'">
            <IconFont
              :type="
                record.status === 1
                  ? 'icon-lizhishenqing'
                  : 'icon-zaizhizhiyuan'
              "
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="setUserStatus(record)"
            />
          </a-tooltip>

          <a-tooltip content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="edit(record.id)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state !== 6" content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="deletePersonnelData(record.id)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { formHeaderSetting } from '@/types/global';
  import {
    GetPersonnelinformation,
    DeletingPersonnel,
    alterPersonnel,
    Getsingleperson,
    addPersonnel,
    // Getdepartment,
    GetRoleInformation,
    putStaffModStatus,
  } from '@/api/home/System settings/personal-information/index';
  import regex from '@/utils/regex';
  import { GetPositioninformation } from '@/api/home/System settings/position-management/index';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure/index';
  import useUser from '@/hooks/user';
  import {
    useAppStore,
    useUserStore,
    useMenusStore,
    useRouterStore,
  } from '@/store';
  import { values } from 'lodash';
  // import { number } from '@intlify/core-base';
  // import { data } from 'vfile';

  const { logout } = useUser();
  const router = useRouter();
  const title = '人员管理';
  const breadCrumb = ['首页', '系统设置', '人员管理'];
  let tableTurnRef: any = ref(); // 储存table的ref
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const fieldNames = { value: 'id', label: 'name' };
  let titleName = ref('新增人员信息');
  let visible = ref(false);
  const formData = ref();

  let form = ref<any>({
    id: '',
    name: '',
    staffNo: '',
    gender: '',
    mobile: '',
    certificateType: '',
    userDepartmentId: null,
    idNumber: '',
    userPositionId: null,
    status: '',
    role: '',
    account: '',
    password: '',
  });

  // 校验手机
  const validatePhone = (val: any, callback: any) => {
    if (val === undefined) callback(new Error('请输入电话号码'));
    else if (!regex.phone.role.test(val)) callback('请输入正确的电话号码');
    return true;
  };

  // 校验身份证
  const validateIdNumber = (val: any, callback: any) => {
    if (val === undefined) callback(new Error('请输入身份证号码'));
    else if (!regex.idNumber.role.test(val)) callback('请输入正确的身份证号码');
    return true;
  };
  // 表单rules
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入姓名',
      },
      {
        maxLength: 16,
        message: '姓名不能超过16位数',
      },
    ],
    mobile: [
      {
        required: true,
        validator: validatePhone,
      },
    ],
    gender: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
    certificateType: [
      {
        required: true,
        message: '请选择证件类型',
      },
    ],
    idNumber: [
      {
        required: true,
        validator: validateIdNumber,
      },
    ],
    role: [
      {
        required: true,
        message: '请选择角色',
      },
    ],
    status: [
      {
        required: true,
        message: '请选择状态',
      },
    ],
  });

  const stationData = ref<any>([]);
  const roleData = ref<any>([]);

  // 储存人员信息
  let clientList = ref([]);

  // 获取人员信息数据
  const Getuserlist = async (pageData?: any) => {
    try {
      const res = await GetPersonnelinformation({
        ...pageData,
      });
      res.content = res.content.data;
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const toTree = (list: any) => {
    // 定义最终需要返回的树形结构数据
    let treeData: any = [];
    // 对传入的数组进行遍历
    list.forEach((item: any) => {
      // 如果pid没有值,那就是顶级对象,直接添加进数组
      if (!item.pid) {
        treeData.push(item);
      }
      // 理解为二次遍历 ：每个对象都找一遍自己的孩子添加到children
      let objList = list.filter((data: any) => data.pid === item.id);
      if (objList.length) {
        item.children = objList;
      }
    });
    return treeData;
  };

  const OrganizationData = ref();
  const GetOrganization = async () => {
    const res = await GetOrganizationchart();
    OrganizationData.value = toTree(res.department);
  };
  GetOrganization();

  // 获取岗位、角色数据
  const getDepartment = async () => {
    const [data, msg] = await Promise.all([
      GetPositioninformation({ page: 1, size: 99999 }),
      GetRoleInformation(),
    ]);
    stationData.value = data.content.filter((i) => i.status === 1);
    roleData.value = msg;
  };

  getDepartment();

  // 点击新建人员
  const add = (): void => {
    visible.value = true;
    titleName.value = '新建人员';
    if (titleName.value === '新建人员') {
      form.value = {
        name: '',
        staffNo: '',
        gender: '',
        mobile: '',
        certificateType: '',
        idNumber: '',
        userPositionId: null,
        status: '',
        role: '',
        account: '',
        password: '',
      };
    }
  };

  const columns = [
    {
      id: 2,
      title: '姓名',
      visible: true,
      type: 'string',
      code: 'name',
    },
    {
      id: 3,
      title: '性别',
      visible: true,
      type: 'string',
      code: 'gender',
    },
    {
      id: 4,
      title: '工号',
      visible: true,
      type: 'string',
      code: 'staffNo',
    },
    {
      id: 5,
      title: '部门',
      visible: true,
      type: 'string',
      code: 'department',
    },
    {
      id: 6,
      title: '岗位',
      visible: true,
      type: 'string',
      code: 'positionId',
    },

    {
      id: 8,
      title: '手机号码',
      visible: true,
      type: 'string',
      code: 'mobile',
    },
    {
      id: 9,
      title: '证件类型',
      visible: true,
      type: 'string',
      code: 'certificateType',
    },
    {
      id: 10,
      title: '证件号码',
      visible: true,
      type: 'string',
      code: 'idNumber',
    },
    {
      id: 11,
      title: '角色',
      visible: true,
      type: 'string',
      code: 'role',
    },
    {
      id: 11,
      title: '状态',
      visible: true,
      type: 'string',
      code: 'state',
    },
    {
      id: 12,
      title: '操作',
      visible: true,
      type: 'string',
      code: 'handle',
    },
  ];

  const selectedHeader = computed(() => {
    return columns.filter((item) => item.visible);
  });

  const handleBeforeOk = async () => {
    formData.value.validate(async (res: unknown) => {
      if (!res) {
        if (titleName.value === '新建人员') {
          await addPersonnel({ ...form.value });
          tableTurnRef.value.loadData();
          visible.value = false;
        } else {
          await alterPersonnel({ ...form.value });
          tableTurnRef.value.loadData();
          visible.value = false;
        }
      } else {
        visible.value = true;
      }
    });
  };

  // 编辑员工信息
  const edit = async (cid: any) => {
    titleName.value = '编辑员工信息';
    visible.value = true;
    const id = {
      id: cid,
    };
    const res = await Getsingleperson(id);
    form.value = res;
  };

  // 删除人员信息
  const deletePersonnelData = async (cid) => {
    const data = {
      id: cid,
    };
    await DeletingPersonnel(data);
    tableTurnRef.value.loadData();
    // const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
    // if (cid === userInfo.id) {
    //   logout();
    // }
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
  });

  const setUserStatus = async (res) => {
    const { id, status } = res;
    await putStaffModStatus({ id, status: status === 1 ? 2 : 1 });
    tableTurnRef.value.loadData();
  };
</script>

<style scoped lang="less">
  .client-list {
    :deep(.arco-space) {
      justify-content: space-between;
    }

    :deep(.arco-space-horizontal .arco-space-item) {
      margin-left: 50px;
    }
  }

  ::v-deep .arco-space-item {
    width: 48%;
  }

  .y_statusBox {
    width: 60px;
    height: 30px;
    background-color: rgba(49, 194, 124, 1);
    border-radius: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }

  .n_statusBox {
    width: 60px;
    height: 30px;
    background-color: rgba(204, 204, 204, 1);
    border-radius: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
  }
</style>
